﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FineUICore
{
    /// <summary>
    /// 扩展
    /// </summary>
    public static class FineUICoreEx
    {
        /// <summary>
        /// 窗口
        /// </summary>
        /// <param name="f">自己</param>
        /// <param name="url">地址</param>
        /// <param name="title">标题</param>
        /// <param name="w">宽度</param>
        /// <param name="h">高度</param>
        /// <returns></returns>
        public static GridExtension EditWindow(this GridExtension f, string url, string title = "编辑", int w = 600, int h = 400)
        {
            WindowExtension window = new WindowExtension(new Window());
            window.ID(f.Source.ID + "_Edit").Width(w).Height(h).Title(title)
            .IconFont(IconFont.Edit).Hidden(true)
            .EnableIFrame(true).IFrameUrl(url);
            string js = "F.ui." + f.Source.ID + ".Window = F.ui." + window.Source.ID + ";";
            js += "F.ui." + f.Source.ID + ".Window.defaultUrl = '" + url + "';";
            PageContext.RegisterStartupScript(js);
            return f;
        }

        public static FormExtension RowsEx(this FormExtension f, int clo, params IControlBaseExtension[] extensions)
        {
            //控件数量
            int count = extensions.Length;
            //行数
            int rowcount = Convert.ToInt32(Math.Ceiling((double)(count / clo)));
            string widths = GetWidthsByClo(clo);
            int c = 0;
            List<FormRowExtension> rows = new List<FormRowExtension>();
            for (int i = 0; i < rowcount; i++)
            {
                FormRowExtension row = new FormRowExtension(new FormRow());
                List<IControlBaseExtension> cbs = new List<IControlBaseExtension>();
                for (int j = i * clo; j < (i + 1) * clo; j++)
                {
                    c++;
                    cbs.Add(extensions[j]);
                }
                row.ColumnWidths(widths).Items(cbs.ToArray());
                rows.Add(row);
            }

            FormRowExtension lastrow = new FormRowExtension(new FormRow());
            List<IControlBaseExtension> lastcs = new List<IControlBaseExtension>();
            for (int i = c; i < count; i++)
            {
                lastcs.Add(extensions[i]);
            }
            lastrow.ColumnWidths(widths).Items(lastcs.ToArray());
            rows.Add(lastrow);
            f.Rows(rows.ToArray());
            return f;
        }

        /// <summary>
        /// 计算列宽
        /// </summary>
        /// <param name="clo"></param>
        /// <returns>xx% xx%</returns>
        private static string GetWidthsByClo(int clo)
        {
            int w = Convert.ToInt32(100 / clo);
            string[] s = Enumerable.Range(1, clo).Select(x => w + "%").ToArray();
            return string.Join(" ", s);
        }
    }
}
